//
//  StatusViewModel.swift
//  WeiBlog
//
//  Created by apple on 15/10/20.
//  Copyright © 2015年 xiang. All rights reserved.
//

import UIKit
import SDWebImage
/// 单条微博视图模型
class StatusViewModel {
    /// 微博模型
    var status:Status
    /// 头像URL
    var iconURL:NSURL?{
        
        return NSURL(string: status.user?.profile_image_url ?? "")
    }
    
    ///发布时间
    var composetTime:String?{
        var str = status.created_at //?? ""
        str = str?.stringByReplacingOccurrencesOfString(" +0800 2015", withString: "")
        str = str?.stringByReplacingCharactersInRange(Range(start: "12345678".startIndex, end: "12345678".endIndex), withString: "")
        return str
    }
    /// 认证类型，-1：没有认证，0，认证用户，2,3,5: 企业认证，220: 达人
    var verifiedImage:UIImage? {
        switch status.user?.verified_type ?? -1{ //注意这里需要加??
        case 2,3,5:
            return UIImage(named: "avatar_enterprise_vip")
        case 220:
            return UIImage(named: "avatar_grassroot")
        case 0:
            return UIImage(named: "avatar_vip")
        default:
            return nil
        }
    }
    
    /// vip图标
    var vipImage:UIImage?{
        
        if status.user?.mbrank >= 0 && status.user?.mbrank < 7{
            
            let level = status.user?.mbrank ?? 0
            return UIImage(named: "common_icon_membership_level\(level)")
        }
        
        return nil
    }
    
    /// 转发微博的正文,如果retweeted_status字段为空,直接返回nil
    var retweetedText:String?{
        
        guard let status = status.retweeted_status else{
            return nil
        }
        
        //是转发微博
        return "@" + (status.user?.screen_name)! + ":" + status.text!
    }
    
    ///当微博是转发微博时,那么retweeted_status字段有值,并且一条微博,只能有一个pic_urls数组有值
    ///转发微博不能配图,如果有图,那么就是转发的微博的图片组
    ///配图的URL数组(定义为存储型属性)
    lazy var imageURLs:[NSURL] = {
        
        var urls = [NSURL]()
        
        //注意一个问题,pic_urls数组不可能为nil,但是可能为空,所以这里的判断就需要考虑
        let urlArr = self.status.pic_urls?.count == 0 ? self.status.retweeted_status?.pic_urls : self.status.pic_urls
        
        for v in urlArr ?? []{
                
            let urlString = v["thumbnail_pic"]
                
            let url = NSURL(string: urlString!)
                
            urls.append(url!)
            
            }
        return urls
    }()
    
    ///StatusCell的高度
    lazy var rowHeight:CGFloat = {
        
        var cell = StatusCell()
        //如果转发微博不是空
        if self.status.retweeted_status != nil{
            
            cell = RetweetedStatusCell(style: .Default, reuseIdentifier: RetweetedCellID)
            
        }else{
            
            cell = MyStatusCell()
        }
    
        cell.viewModel = self
        
        return cell.rowHeight!
        
        }()
    
    init(status:Status){
        
        self.status = status
    
    }
}